<?php

use console\db\Migration;

/**
 * 创建用户成长日志数据相关信息表
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m180201_103001_t_account_log_sequence extends Migration {

    /**
     * @var string 默认使用事务性表存储引擎
     */
    public $tableEngine = parent::ENGINE_MYISAM;

    /**
     * {@inheritdoc}
     */
    public function up() {

        /**
         * 成长日志表
         * @table `trend_log`.
         */
        $columns = [
            'id' => $this->primaryKey(),
            'user_id' => $this->integer(11)->unsigned()->notNull()->defaultValue(0)->comment('用户ID'),
            'type' => $this->char(20)->notNull()->defaultValue('')->comment('用户ID'),
            'num' => $this->integer(11)->notNull()->defaultValue(0)->comment('数量'),
            'current' => $this->integer(11)->notNull()->defaultValue(0)->comment('当前账户'),
            'rule_id' => $this->tinyint(4)->unsigned()->notNull()->defaultValue(0)->comment('获取规则ID'),
            'mark' => $this->string(255)->defaultValue('')->comment('日志描述'),
            'created_at' => $this->unixTimestamp()->comment('获取时间'),
        ];
        $indexs = [
            [
                'columns' => 'user_id',
            ],
            [
                'columns' => 'type',
            ],
            [
                'columns' => 'created_at',
            ],
            [
                'columns' => 'rule_id',
            ],
        ];
        $tables = [];
        for ($i = 0; $i < 4; $i++) {
            $tindex = 2016 + $i;
            $this->tableBuilder([
                'name' => 'trend_log_' . $tindex,
                'comment' => '成长日志表',
                'columns' => $columns,
                'index' => $indexs
            ]);
            $tables[] = $this->db->getSchema()->getRawTableName('{{%trend_log_' . $tindex . '}}');
        }
        $union = implode(',', $tables);
        $tableOptions = 'ENGINE=MERGE UNION=(' . $union . ') INSERT_METHOD=LAST';
        $this->tableBuilder([
            'name' => 'trend_log',
            'comment' => '成长日志表',
            'columns' => $columns,
            'index' => $indexs
        ]);
        $this->db->createCommand('ALTER TABLE {{%trend_log}} ' . $tableOptions)->execute();
    }

    /**
     * {@inheritdoc}
     */
    public function down() {
        $this->dropTable('{{%trend_log_2019}}');
        $this->dropTable('{{%trend_log_2018}}');
        $this->dropTable('{{%trend_log_2017}}');
        $this->dropTable('{{%trend_log_2016}}');
        $this->dropTable('{{%trend_log}}');
    }

}
